﻿using System;
using System.Windows;
using System.Windows.Input;
using Microsoft.Win32;

using Core.Logic;
using Core.Localization;
using UI.Resources.Controls;

namespace UI.Windows.Dialogs 
{
	public partial class ImportExportDialogWindow 
	{
		public ImportExportDialogWindow(OptionsManager optionsManager, LocalizationManager localizationManager) 
		{
			InitializeComponent();

			_optionsManager = optionsManager;
			_localizationManager = localizationManager;
		}

		#region Private properties

		private readonly OptionsManager _optionsManager;

		private readonly LocalizationManager _localizationManager;

		private string _path;

		#endregion

		#region Commands

		public static readonly RoutedCommand ImportOptionsCommand = new RoutedCommand("ImportOptionsCommand", typeof(ImportExportDialogWindow));

		public static readonly RoutedCommand ExportOptionsCommand = new RoutedCommand("ExportOptionsCommand", typeof(ImportExportDialogWindow));

		#endregion

		#region Commands handlers

		private void ImportOptionsCommandExecuted(object sender, ExecutedRoutedEventArgs e)
		{
			string errorLabel = _localizationManager.Localize("RAE:Strings:Warning");
			string errorText = _localizationManager.Localize("RAE:Strings:TEXT_Import_options");
			new WarningMessageBox(errorLabel, errorText).Show(() => {
				_optionsManager.LoadOptions(_path);

				string messageLabel = _localizationManager.Localize("RAE:Strings:Success");
				string messageText = _localizationManager.Localize("RAE:Strings:TEXT_Success");
				MessageBox.Show(messageText, messageLabel, MessageBoxButton.OK, MessageBoxImage.Information);

				DialogResult = true;
				Close();
			});
		}

		private void ExportDialogCommandExecuted(object sender, ExecutedRoutedEventArgs e)
		{
			_optionsManager.SaveOptions(_path);

			string messageLabel = _localizationManager.Localize("RAE:Strings:Success");
			string messageText = _localizationManager.Localize("RAE:Strings:TEXT_Success");
			MessageBox.Show(messageText, messageLabel, MessageBoxButton.OK, MessageBoxImage.Information);

			DialogResult = true;
			Close();
		}

		private void FilePathNonEmptyCanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = !String.IsNullOrEmpty(_path);
		}

		#endregion

		#region Event handlers

		private void OpenSaveFileDialogButtonClick(object sender, RoutedEventArgs e)
		{
			var fileDialog = new OpenFileDialog
			{
				Title = "Choose location...",
				Filter = "All files (*.*)|*.*|Project files (*.xml)|*.xml",
				FilterIndex = 2,
				CheckFileExists = false
			};

			if (fileDialog.ShowDialog(this).Value)
			{
				_path = fileDialog.FileName;
				PathWatermarkTextBox.Text = _path;
			}
		}

		private void  CancelButtonClick(object sender, RoutedEventArgs e)
		{
			DialogResult = false;
			Close();
		}

		#endregion
	}
}